﻿using PluginAPI.Core;
using PluginAPI.Core.Attributes;
using PluginAPI.Enums;
using PluginAPI.Events;
using ReconnectRole.Data;
using ReconnectRole.Main;
using System;
using UnityEngine;
using Utils;



namespace ReconnectRole
{
    /// <summary>
    /// 
    /// </summary>
    public class ReconnectEvent
    {
        [PluginEvent(ServerEventType.PlayerSpawn)]
        public void OnPlayerSpawn(PlayerSpawnEvent ev)
        {
            TimeCoroutine.Delay(5f, () =>
            {
                if (ev.Player.Team != PlayerRoles.Team.SCPs) return;

                RoleInfo roleInfo = new RoleInfo();
                {
                    roleInfo.SteamID = ev.Player.UserId;
                    roleInfo.RoleTypeId = ev.Player.Role;
                    roleInfo.Health = ev.Player.Health;
                    roleInfo.Position = ev.Player.Position;
                    roleInfo.LeftTime = DateTime.Now;
                }
     
                CodeLoad.Singleton.Reconnect.DoRecord(roleInfo);
            });
        }

        [PluginEvent(ServerEventType.TeamRespawn)]
        public void OnTeamRespawn(TeamRespawnEvent ev)
        {
            CodeLoad.Singleton.Reconnect.DoUpdate();
        }

        [PluginEvent(ServerEventType.PlayerDying)]
        public void OnPlayerDying(PlayerDyingEvent ev)
        {
            CodeLoad.Singleton.Reconnect.DoRemove(ev.Player.UserId);

            if (ev.Player.Team == PlayerRoles.Team.SCPs)
            {
                CodeLoad.Singleton.Reconnect.DoRemove(ev.Player.UserId);
            }

            if (ev.Attacker.Team != PlayerRoles.Team.SCPs) return;
            
            CodeLoad.Singleton.Reconnect.DoUpdate();
        }

        [PluginEvent(ServerEventType.PlayerJoined)]
        public void OnPlayerJoined(PlayerJoinedEvent ev)
        {
            TimeCoroutine.Delay(1f, () =>
            {
                // 校验缓存是否有该橘色
                bool isContains = CodeLoad.Singleton.Reconnect.TryRead(ev.Player.UserId, out var output);
                if (!isContains) return;

                // 校验信息时效性
                double duration = (DateTime.Now - output.LeftTime).TotalSeconds;
                bool canAct = duration <= CodeLoad.Singleton.Config.EffectiveSeconds;

                if (!canAct)
                {
                    CodeLoad.Singleton.Reconnect.DoRemove(ev.Player.UserId);

                    string negative =
                        $"嘿！你的信息已无效" +
                        $"| 时间占比：[{duration}s / {CodeLoad.Singleton.Config.EffectiveSeconds}s]" +
                        $"| 如有疑问请向管理员申诉";

                    MessageStringUtils.GenerateAdminMessage(negative, out string negativeNotice);
                    ev.Player.SendBroadcast(negativeNotice, 15, Broadcast.BroadcastFlags.Normal, true);

                    return;
                }


                string messageBroadcast = $"请注意！[断线] <color=red>{output.RoleTypeId}</color> 已返回服务器，即将加入战局";
                MessageStringUtils.GenerateAdminMessage(messageBroadcast, out string messageBc);
                Server.SendBroadcast(messageBc, 15, Broadcast.BroadcastFlags.Truncated, true);


                string message = $"嘿！你的有效信息已查询！即将分配上次断线前角色 [<color=red>{output.RoleTypeId}</color>]";
                MessageStringUtils.GenerateAdminMessage(message, out string notice);
                ev.Player.SendBroadcast(notice, 15, Broadcast.BroadcastFlags.Normal, true);

                TimeCoroutine.Delay(15f, () =>
                {
                    ev.Player.SetRole(output.RoleTypeId, PlayerRoles.RoleChangeReason.LateJoin);
                    ev.Player.Position = output.Position + Vector3.up;

                    Log.Info($"日志|记录生命值[{output.Health}]|当前生命值[{ev.Player.Health}]");

                    float reduceHP = Mathf.Clamp(ev.Player.Health - output.Health, 0, float.MaxValue);
                    ev.Player.Damage(reduceHP, "断线重连|生命值调整", "");

                    Log.Info($"日志|累计扣除：[{reduceHP}]");
                });

            });
        }

        [PluginEvent(ServerEventType.RoundEnd)]
        public void OnRoundEnd(RoundEndEvent ev)
        {
            CodeLoad.Singleton.Reconnect.DoClear();
        }

        [PluginEvent(ServerEventType.RoundRestart)]
        public void OnRoundRestart(RoundRestartEvent ev)
        {
            CodeLoad.Singleton.Reconnect.DoClear();
        }



        [PluginEvent(ServerEventType.PlayerLeft)]
        public void OnPlayerLeft(PlayerLeftEvent ev)
        {
            if (ev.Player.Team != PlayerRoles.Team.SCPs) return;

            RoleInfo role = new RoleInfo();
            {
                role.Health = ev.Player.Health;
                role.SteamID = ev.Player.UserId;
                role.LeftTime = System.DateTime.Now;
                role.RoleTypeId = ev.Player.Role;
                role.Position = role.Position;
            }

            Log.Info($"重连分配|缓存|{role.SteamID}|{role.RoleTypeId}");

            CodeLoad.Singleton.Reconnect.DoRecord(role);
        }
    }
}
